﻿using Microsoft.Practices.EnterpriseLibrary.Validation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Utilities
{
    public class ErpErrorHandler
    {
        // Fields
        private static string _Code = "";
        private static string _description = string.Empty;
        private static bool _hasErrors = false;
        private static Exception _innerException;
        private static object _source = "";
        private static string _strMessage = string.Empty;

        // Methods
        public static void AddExceptionErrorEntry(Exception ex)
        {
            _Code = ex.GetType().GUID.ToString().ToUpper();
            _strMessage = ex.Message;
            WriteLogs(ex);
            _hasErrors = true;
        }

        public static void AddSQLErrorNumber(string strSQLErrorNumber)
        {
            WriteLogs(strSQLErrorNumber);
            if (strSQLErrorNumber.StartsWith("Exception:"))
            {
                strSQLErrorNumber = strSQLErrorNumber.Substring("Exception:".Length);
            }
            else if (strSQLErrorNumber.StartsWith("Error:"))
            {
                strSQLErrorNumber = strSQLErrorNumber.Substring("Error:".Length);
            }
            string[] strArray = strSQLErrorNumber.Split(new char[] { '@' });
            if (strArray.Length > 0)
            {
                string strTag = "SQL_" + strArray[0];
                _strMessage = ErpMultiLanguage.GetString("SQLERRORS", strTag);
                if (_strMessage == strTag)
                {
                    _strMessage = ErpMultiLanguage.GetString("SQLERRORS", "SQL_NA");
                    _strMessage = string.Format(_strMessage, strTag);
                }
            }
            if (strArray.Length > 1)
            {
                _source = strArray[1];
            }
            _hasErrors = true;
        }

        public static void AddValidationErrorEntry(ValidationResult result)
        {
        }

        public static void ClearErrors()
        {
            _innerException = null;
            _description = string.Empty;
            _hasErrors = false;
        }

        private static string FormatExceptionDescription(Exception e)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("===================================== ErrorHandler =====================================" + Environment.NewLine);
            builder.Append("== Time of Error: " + DateTime.Now.ToString("g") + Environment.NewLine);
            while (e != null)
            {
                builder.Append("== Code: " + _Code + Environment.NewLine);
                builder.Append("== Message: " + e.Message + Environment.NewLine);
                builder.Append("== Source: " + e.Source + Environment.NewLine);
                builder.Append("== TargetSite: " + e.TargetSite + Environment.NewLine);
                builder.Append("== StackTrace: " + e.StackTrace + Environment.NewLine);
                e = e.InnerException;
            }
            builder.Append("===================================== ErrorHandler =====================================" + Environment.NewLine + Environment.NewLine + Environment.NewLine);
            return builder.ToString();
        }

        private static string FormatExceptionDescription(string strLogs)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("===================================== ErrorHandler =====================================" + Environment.NewLine);
            builder.Append("== Time of Error: " + DateTime.Now.ToString("g") + Environment.NewLine);
            builder.Append("== Message: " + strLogs + Environment.NewLine);
            builder.Append("===================================== ErrorHandler =====================================" + Environment.NewLine + Environment.NewLine + Environment.NewLine);
            return builder.ToString();
        }

        public static void HandleException(Exception ex)
        {
            AddExceptionErrorEntry(ex);
            new frmShowMessageDialogEx().ShowDialog(ErpMultiLanguage.GetString("MESSAGEBOX", _Code, Message), ErpMultiLanguage.GetString("COMMON", "ERROR_DIALOG_TITLE"), MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
        }

        public static void WriteLogs(Exception ex)
        {
            string str = DateTime.Today.ToString("yyyyMM");
            string str2 = FormatExceptionDescription(ex);
            if (!Directory.Exists(Application.StartupPath + @"\Logs\"))
            {
                Directory.CreateDirectory(Application.StartupPath + @"\Logs\");
                File.Create(Application.StartupPath + @"\Logs\Errors_" + str + ".txt");
                string path = Application.StartupPath + @"\Logs\Errors_" + str + ".txt";
                try
                {
                    FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write);
                    StreamWriter writer = new StreamWriter(stream);
                    writer.Write(str2);
                    writer.Close();
                    stream.Close();
                }
                catch
                {
                }
            }
            else
            {
                if (!File.Exists(Application.StartupPath + @"\Logs\Errors_" + str + ".txt"))
                {
                    File.Create(Application.StartupPath + @"\Logs\Errors_" + str + ".txt");
                }
                string str4 = Application.StartupPath + @"\Logs\Errors_" + str + ".txt";
                try
                {
                    FileStream stream2 = new FileStream(str4, FileMode.Append, FileAccess.Write);
                    StreamWriter writer2 = new StreamWriter(stream2);
                    writer2.Write(str2);
                    writer2.Close();
                    stream2.Close();
                }
                catch
                {
                }
            }
        }

        public static void WriteLogs(string strLogs)
        {
            string str = DateTime.Today.ToString("yyyyMM");
            string str2 = FormatExceptionDescription(strLogs);
            if (!Directory.Exists(Application.StartupPath + @"\Logs\"))
            {
                Directory.CreateDirectory(Application.StartupPath + @"\Logs\");
                File.Create(Application.StartupPath + @"\Logs\Errors_" + str + ".txt");
                string path = Application.StartupPath + @"\Logs\Errors_" + str + ".txt";
                try
                {
                    FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write);
                    StreamWriter writer = new StreamWriter(stream);
                    writer.Write(str2);
                    writer.Close();
                    stream.Close();
                }
                catch
                {
                }
            }
            else
            {
                if (!File.Exists(Application.StartupPath + @"\Logs\Errors_" + str + ".txt"))
                {
                    File.Create(Application.StartupPath + @"\Logs\Errors_" + str + ".txt");
                }
                string str4 = Application.StartupPath + @"\Logs\Errors_" + str + ".txt";
                try
                {
                    FileStream stream2 = new FileStream(str4, FileMode.Append, FileAccess.Write);
                    StreamWriter writer2 = new StreamWriter(stream2);
                    writer2.Write(str2);
                    writer2.Close();
                    stream2.Close();
                }
                catch
                {
                }
            }
        }

        // Properties
        public static object Code
        {
            get
            {
                return _Code;
            }
        }

        public static string Description
        {
            get
            {
                return _description;
            }
        }

        public static ValidationResults Errors
        {
            get
            {
                ValidationResults results = new ValidationResults();
                ValidationResult validationResult = new ValidationResult(_strMessage, _source, "", "", null);
                results.AddResult(validationResult);
                return results;
            }
        }

        public static bool HasErrors
        {
            get
            {
                return _hasErrors;
            }
        }

        public static Exception InnerException
        {
            get
            {
                return _innerException;
            }
        }

        public static string Message
        {
            get
            {
                return _strMessage;
            }
        }

        public static object Source
        {
            get
            {
                return _source;
            }
        }

        public static string StringErrors
        {
            get
            {
                string str = _strMessage;
                if (!_source.ToString().Trim().Equals(""))
                {
                    str = str + " : " + _source.ToString();
                }
                return str;
            }
        }
    }


}
